import { Server as SocketIOServer } from 'socket.io'
import { Server as HTTPServer } from 'http'
import type { Player } from '@dx-fun-group/shared-types'

export interface GroupingState {
  groups: Array<{ players: Player[] }>
  lastUpdate: string
  connectedUsers: number
}

class GroupingService {
  private io: SocketIOServer | null = null
  private groupingState: GroupingState = {
    groups: Array.from({ length: 8 }, () => ({ players: [] })),
    lastUpdate: new Date().toISOString(),
    connectedUsers: 0
  }

  initialize(server: HTTPServer) {
    this.io = new SocketIOServer(server, {
      cors: {
        origin: ["http://localhost:5173", "http://47.109.186.175", "http://47.109.186.175:8123"],
        methods: ["GET", "POST"]
      }
    })

    this.io.on('connection', (socket) => {
      console.log(`用户连接: ${socket.id}`)
      if (this.io) {
        this.groupingState.connectedUsers = this.io.sockets.sockets.size
        // 广播更新后的连接人数
        this.io.emit('grouping_update', this.groupingState)
      }
      this.handleConnection(socket)
    })
  }

  private handleConnection(socket: any) {
    // 更新连接人数
    if (this.io) {
      this.groupingState.connectedUsers = this.io.sockets.sockets.size
    }
    // 发送当前分组状态给新连接的用户
    socket.emit('grouping_state', this.groupingState)

    // 处理分组更新
    socket.on('player_moved', (data: {
      player: Player
      fromGroup: number | null
      toGroup: number
    }) => {
      this.handlePlayerMoved(data)
    })

    // 处理分组重置
    socket.on('groups_reset', () => {
      this.handleGroupsReset()
    })

    // 处理用户断开连接
    socket.on('disconnect', () => {
      console.log(`用户断开连接: ${socket.id}`)
      if (this.io) {
        this.groupingState.connectedUsers = this.io.sockets.sockets.size
        // 广播更新后的连接人数
        this.io.emit('grouping_update', this.groupingState)
      }
    })
  }

  private handlePlayerMoved(data: {
    player: Player
    fromGroup: number | null
    toGroup: number
  }) {
    const { player, fromGroup, toGroup } = data

    // 从原分组移除
    if (fromGroup !== null && fromGroup >= 0) {
      const fromGroupData = this.groupingState.groups[fromGroup]
      if (fromGroupData) {
        fromGroupData.players = fromGroupData.players.filter(p => p.id !== player.id)
      }
    }

    // 添加到目标分组
    if (toGroup >= 0) {
      const toGroupData = this.groupingState.groups[toGroup]
      if (toGroupData && toGroupData.players.length < 8) {
        toGroupData.players.push(player)
      }
    }

    this.updateGroupingState()
  }

  private handleGroupsReset() {
    this.groupingState.groups = Array.from({ length: 8 }, () => ({ players: [] }))
    this.updateGroupingState()
  }

  private updateGroupingState() {
    this.groupingState.lastUpdate = new Date().toISOString()
    
    // 更新连接人数
    if (this.io) {
      this.groupingState.connectedUsers = this.io.sockets.sockets.size
    }
    
    // 广播给所有连接的客户端
    if (this.io) {
      this.io.emit('grouping_update', this.groupingState)
    }
  }



  // 获取当前分组状态
  getGroupingState(): GroupingState {
    // 确保在返回状态前更新连接人数
    if (this.io) {
      this.groupingState.connectedUsers = this.io.sockets.sockets.size
      console.log(`📊 当前连接人数: ${this.groupingState.connectedUsers}`)
    } else {
      console.log('⚠️  WebSocket未初始化，io为null')
    }
    return this.groupingState
  }

  // 手动更新分组状态（用于测试）
  updateGroups(groups: Array<{ players: Player[] }>) {
    this.groupingState.groups = groups
    this.updateGroupingState()
  }
}

export const groupingService = new GroupingService()
